# encoding: utf-8
"""
@author: 夏洛
@QQ: 1972386194
@file: 03-demo2.py
"""
import requests

'''
获取cookie信息  httponly 有 √ 表示后台返回  可以访问地址进行截获

http://www.zjmazhang.gov.cn/hdjlpt/published?via=pc
    获取cookie

http://www.zjmazhang.gov.cn/hdjlpt/letter/pubList"
    携带cookie
    获取数据

cookie 反爬虫  token字样  cookie 有一串很长的 乱码   没有固定的方法 就是测试
    
X-CSRF-TOKEN  90% 会出现在 html页面   CSRF 请求伪造技术

'''

headers = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6",
    "Connection": "keep-alive",
    "Content-Type": "application/x-www-form-urlencoded",
    "Origin": "http://www.zjmazhang.gov.cn",
    "Referer": "http://www.zjmazhang.gov.cn/",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36",
}
import re
def get_cookie():
    url = 'http://www.zjmazhang.gov.cn/hdjlpt/published?via=pc'
    res = requests.get(url,headers=headers)
    session = res.cookies.get('szxx_session')     # k v 形式
    token = re.findall(r"var _CSRF = '(.*?)';",res.text)
    if token:
        token = token[0]
    return session,token

def  get_data():
    s,t = get_cookie()
    cookies = {
        "szxx_session":s
    }
    headers['X-CSRF-TOKEN'] = t
    url = "http://www.zjmazhang.gov.cn/hdjlpt/letter/pubList"
    print(cookies)
    print(headers)
    data = {
        "offset": "0",
        "limit": "20",
        "site_id": "759010"
    }
    response = requests.post(url, headers=headers, cookies=cookies, data=data, verify=False)
    print(response.text)
get_data()
